package com.work.formaldehyde.activity;

import android.app.Activity;
import android.app.ActivityOptions;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.umeng.analytics.MobclickAgent;
import com.work.formaldehyde.R;
import com.work.formaldehyde.util.ApiUtils;
import com.work.formaldehyde.util.Url;

import org.json.JSONObject;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;


public class CompostActivity extends Activity implements View.OnClickListener {
    private File fl;
    private ImageView comeback, getpostimg, gouwuche_img;
    private RelativeLayout fankui_tijiao, postimgs;
    private EditText fankui_edittext;
    private String Edtextstr;
    private String url = "";
    private TextView shangpingmingzi;

    private static ProgressDialog mSaveDialog = null;
    private String shangpingid = "";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ApiUtils.ActivityIsLogin(this, 1);
        setContentView(R.layout.activity_compost);
        comeback = findViewById(R.id.jiance_comeback);
        comeback.setOnClickListener(this);
        if (ApiUtils.isNetworkConnected(CompostActivity.this))
            init();
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }
    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }
    /**
     * 初始加载
     */
    public void init() {
        Intent getmsg = getIntent();
        shangpingid = getmsg.getStringExtra("shangpingid");
        postimgs = findViewById(R.id.postimgs);
        postimgs.setOnClickListener(this);
        fankui_edittext=findViewById(R.id.fankui_edittext);
        fankui_tijiao = findViewById(R.id.fankui_tijiao);
        fankui_tijiao.setOnClickListener(this);
        getpostimg = findViewById(R.id.getpostimg);
        gouwuche_img = findViewById(R.id.gouwuche_img);
        shangpingmingzi = findViewById(R.id.shangpingmingzi);
        shangpingmingzi.setText(getmsg.getStringExtra("shangpingname"));
        ApiUtils.GET_IMAGE(CompostActivity.this, getmsg.getStringExtra("url"), gouwuche_img);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.jiance_comeback:
                onBackPressed();
                break;
            case R.id.postimgs:
                Intent intent = new Intent(Intent.ACTION_PICK, null);
                intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                startActivityForResult(intent, 2);
                break;
            case R.id.getpostimg:
                Intent intents = new Intent(Intent.ACTION_PICK, null);
                intents.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                startActivityForResult(intents, 2);
                break;
            case R.id.fankui_tijiao:
                Edtextstr = fankui_edittext.getText().toString();
                if (!Url.USER_ID.equals("")) {
                    if (Edtextstr.equals("")) {
                        Toast.makeText(CompostActivity.this, R.string.edtext_null,
                                Toast.LENGTH_SHORT).show();
                    } else {
                        ApiUtils.windows(CompostActivity.this, fankui_tijiao, "正在提交");
                        new Handler().postDelayed(new Runnable() {
                            public void run() {
                                ApiUtils.closepopup();
                            }
                        }, 10000);
                        postfile(filesa);
//                        okHttp_postFromParameters();
                    }
                } else {
                    Intent is_login = new Intent(CompostActivity.this, LoginActivity.class);
                    startActivity(is_login, ActivityOptions.makeSceneTransitionAnimation(CompostActivity.this).toBundle());
                    ApiUtils.SetToast(CompostActivity.this, "请先登录");
                }
                break;
        }
    }

    public boolean onKeyUp(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                onBackPressed();
                break;
        }
        return super.onKeyUp(keyCode, event);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 2) {
            // 从相册返回的数据
            if (data != null) {
                // 得到图片的全路径
                Uri uri = data.getData();
                getpostimg.setVisibility(View.VISIBLE);
                postimgs.setVisibility(View.GONE);
                getpostimg.setImageURI(uri);
                url = uri.toString();
                filesa = uri2File(uri);
                String[] filePathColumn = {MediaStore.Images.Media.DATA};
                Cursor cursor = getContentResolver().query(uri, filePathColumn, null, null, null);
                cursor.moveToFirst();
                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                String picPath = cursor.getString(columnIndex);
                //转码
                try {
                    String encode = URLEncoder.encode(picPath, "utf-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                cursor.close();
                if (picPath.equals("")) return;
            }
        }
    }

    public File filesa;
    /**
     * user转换为file文件
     * 返回值为file类型
     *
     * @param uri
     * @return
     */
    private File uri2File(Uri uri) {
        String img_path;
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor actualimagecursor = managedQuery(uri, proj, null,
                null, null);
        if (actualimagecursor == null) {
            img_path = uri.getPath();
        } else {
            int actual_image_column_index = actualimagecursor
                    .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            actualimagecursor.moveToFirst();
            img_path = actualimagecursor
                    .getString(actual_image_column_index);
        }
        File file = new File(img_path);
        return file;
    }

    public void postfile(final File file) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient okHttpClient = new OkHttpClient();
                    MediaType MEDIA_TYPE_MARKDOWN = MediaType.parse("text/x-markdown; charset=utf-8");
                    RequestBody requestBody;
                    if(file!=null) {
                         requestBody = new MultipartBody.Builder()
                                .setType(MultipartBody.FORM)
                                .addFormDataPart("uid", Url.USER_ID)
                                .addFormDataPart("logintoken", Url.LOGIN_TOKEN)
                                .addFormDataPart("goods_id", shangpingid)
                                .addFormDataPart("comment", Edtextstr)
                                .addFormDataPart("images", file.getName(), RequestBody.create(MEDIA_TYPE_MARKDOWN, file))
                                .build();
                    }else{
                         requestBody = new MultipartBody.Builder()
                                .setType(MultipartBody.FORM)
                                .addFormDataPart("uid", Url.USER_ID)
                                .addFormDataPart("logintoken", Url.LOGIN_TOKEN)
                                .addFormDataPart("goods_id", shangpingid)
                                .addFormDataPart("comment", Edtextstr)
                                .addFormDataPart("images", "")
                                .build();
                    }
                    Request request = new Request.Builder()
                            .url(Url.ADDPINGLUN)
                            .post(requestBody)
                            .build();
                    okhttp3.Response response = okHttpClient.newCall(request).execute();
                    String msg = response.body().string();
                    Message message = new Message();
                    message.obj = msg;
                    gethot1.sendMessage(message);
                } catch (
                        Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void okHttp_postFromParameters() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient okHttpClient = new OkHttpClient();
                    RequestBody formBody = new FormBody.Builder().add("uid", Url.USER_ID).add("logintoken", Url.LOGIN_TOKEN).add("goods_id", shangpingid).add("comment", Edtextstr).add("images", url)
                            .build();
                    Request request = new Request.Builder().url(Url.ADDPINGLUN).post(formBody).build();
                    okhttp3.Response response = okHttpClient.newCall(request).execute();
                    String msg = response.body().string();
                    Message message = new Message();
                    message.obj = msg;
                    gethot1.sendMessage(message);
                } catch (
                        Exception e) {
                    e.printStackTrace();
                }
            }
        }).
                start();
    }

    public Handler gethot1 = new Handler() {
        public void handleMessage(Message msg) {
            JSONObject success_Object;
            try {
                if (msg.obj != null) {
                    ApiUtils.closepopup();
                    success_Object = new JSONObject(msg.obj.toString());
                    String code = success_Object.getString("code");
                    if (code.equals("1")) {
                        onBackPressed();
                        ApiUtils.SetToast(CompostActivity.this, "提交成功");
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

}
